// DlgAlterPassword.cpp : 实现文件
//
#define NOMINMAX
#include "DlgAlterPassword.h"

#include <auth/ServerInfo.h>
#include <core/Utility.h>
#include <qbprotocol/include/SSMsgStruct.h>
#include <qbprotocol/include/rdProto.h>
#include <qbtools/message/MessagePoster.h>
#include <uam/UserAccountManager.h>
#include <widgets/SPopupWindow.h>

#include <QByteArray>
#include <QColor>
#include <QFontMetrics>
#include <QPainter>
#include <QStylePainter>

#include "../../../core/strings/md5.h"
#include "../StringResource.h"
#include "auth/MessageProcess.h"

// CDlgAlterPassword 对话框
namespace {
const int BUTTONIDPSOK = 13005;
const int BUTTONIDPSCANCEL = 13006;

const UINT nNum = 0x1;
const UINT nChat = 0x2;
const UINT nBoth = 0x3;

const int nMinSize = 8;
const int nMaxSize = 20;
}  // namespace

CDlgAlterPassword::CDlgAlterPassword(QWidget* parent) : SPopupWindow(parent) {
  setWindowFlag(Qt::FramelessWindowHint);
  setAttribute(Qt::WA_TranslucentBackground);
  setFixedSize(316, 202);

  m_pimgBtnNormal = ImgMgr::instance().image("guiframe_button_default");
  m_btnOk = NULL;
  m_btnCancel = NULL;
  for (int i = 0; i < 3; i++) arrEdit[i] = NULL;
  m_strTip = tr("");
  m_fontSize = 120;

  CreateButton();
  int w = GetMaxWidth();
  CreateEditCtrl(w);

  m_currentFont = font();
  m_currentFont.setBold(false);
  m_currentFont.setPixelSize(13);

  setTitle(NewStringTable::strAIPanelInfo(5));  // 修改密码

  connect(m_btnOk, &QPushButton::clicked, this, &CDlgAlterPassword::OnBtnOk);
  connect(m_btnCancel, &QPushButton::clicked, this,
          &CDlgAlterPassword::OnBtnCancel);
  connect(this, &CDlgAlterPassword::modifySucceed, this,
          &CDlgAlterPassword::onAckDataArrived);
}

CDlgAlterPassword::~CDlgAlterPassword() {}

void CDlgAlterPassword::onDataArrived(const qb::SSAckMsg& msg) {
  ResponseAlterAccount(msg);
  return;
}

int CDlgAlterPassword::SavePassword(std::string strPassword) {
  QuoteServerInfo::instance().savepwd(strPassword);
  return 1;
}

void CDlgAlterPassword::onAckDataArrived(int errCode) {
  if (errCode == 0) {
    DisplayTipError(tr(""));
    QMessageBox::information(this, "提示",
                             NewStringTable::strDlgAlterPassword(0));
  }

  SetEnableBtn(true);
}

void CDlgAlterPassword::ResponseAlterAccount(const qb::SSAckMsg& msg) {
  int nErrorCode = msg.m_ErrorCode;
  if (msg.m_FuncID == E_FID_QB_MODIFY_PASSWORD) {
    switch (nErrorCode) {
      case 0:  // 成功
      {
        SSUserAccountManager::instance().SetUserInfo(msg.m_pRet, msg.m_FuncID);

        std::string str = m_NewPass.toStdString();
        SavePassword(str);

        emit modifySucceed(nErrorCode);
      } break;
      default:  // 失败
      {
        m_strTip = NewStringTable::strDlgAlterPassword(1);  //"修改失败!");
        // update(&m_rcTip);
        emit modifySucceed(nErrorCode);
      }
    }
  }
}

int CDlgAlterPassword::GetMaxWidth() {
  QString szTitle;
  int W;
  {                                                     // 测距
    szTitle = NewStringTable::strDlgAlterPassword(11);  //_T("原密码 : ");

    QFontMetrics fontMetrics(m_currentFont);
    int nFontWidth = fontMetrics.width(szTitle);

    W = nFontWidth;

    szTitle = NewStringTable::strDlgAlterPassword(12);  //_T("新密码 : ");
    fontMetrics = QFontMetrics(m_currentFont);
    nFontWidth = fontMetrics.width(szTitle);
    W = std::max((int)nFontWidth, W);

    szTitle = NewStringTable::strDlgAlterPassword(13);  //_T("确认密码 : ");
    fontMetrics = QFontMetrics(m_currentFont);
    nFontWidth = fontMetrics.width(szTitle);
    W = std::max((int)nFontWidth, W);
  }

  return W;
}

int CDlgAlterPassword::GetMaxHeight() {
  QString szTitle;
  // 测距
  szTitle = NewStringTable::strDlgAlterPassword(11);  //_T("原密码 : ");
  QFontMetrics fontMetrics(m_currentFont);
  int nFontWidth = fontMetrics.width(szTitle);
  int nFontheight = fontMetrics.height();
  return nFontheight;
}

void CDlgAlterPassword::resizeEvent(QResizeEvent* event) {
  QRect r = rect();

  int left = r.left() + (r.right() - r.left() - 120 - 80 - 8) / 2;
  m_btnCancel->move(left, r.bottom() - 28);
  m_btnOk->move(left + 80 + 8, r.bottom() - 28);

  int W, fontHeight;
  W = GetMaxWidth();
  fontHeight = GetMaxHeight();

  int X = r.left() + W + 20;
  int editHeight = 24;
  int lineHeight = editHeight + 10;
  r.setTop(r.top() + 8 * 2 + 30);

  rcEdit.setLeft(X + 5);
  rcEdit.setTop((long)(r.top() + (fontHeight - editHeight) / 2));
  rcEdit.setRight(r.right() - 20);
  rcEdit.setBottom(rcEdit.top() + editHeight);

  if (arrEdit[0]) {
    arrEdit[0]->setFixedSize(rcEdit.right() - rcEdit.left(), 24);
    arrEdit[0]->move(rcEdit.left(), rcEdit.top());
  }

  rcEdit.adjust(0, lineHeight, 0, lineHeight);
  if (arrEdit[1]) arrEdit[1]->setFixedSize(rcEdit.right() - rcEdit.left(), 24);
  arrEdit[1]->move(rcEdit.left(), rcEdit.top());

  rcEdit.adjust(0, lineHeight, 0, lineHeight);
  if (arrEdit[2]) arrEdit[2]->setFixedSize(rcEdit.right() - rcEdit.left(), 24);
  arrEdit[2]->move(rcEdit.left(), rcEdit.top());
}

void CDlgAlterPassword::DrawMain() {
  QPainter painter(this);

  QRect rcOk, rcCancel;
  int nGap = 8;
  int nTitleHeight = 30;

  //////////CONTENT
  QColor crText = NAME_COLOR("TextNormal");
  QColor crTip = QColor(255, 0, 0);

  int editHeight = 24;
  int lineHeight = editHeight + 10;
  QString szTitle;
  int W, fontHeight;
  W = GetMaxWidth();
  fontHeight = GetMaxHeight();

  QRect r = rect();
  QRect rcTitle = r;
  int X = r.left() + W + 20;
  rcTitle.setTop(rcTitle.top() + nGap * 2 + nTitleHeight);
  rcTitle.setRight(X);
  rcTitle.setBottom(rcTitle.top() + fontHeight);

  // 原密码
  szTitle = NewStringTable::strDlgAlterPassword(11);  //_T("原密码 : ");

  QRect textRect(rcTitle.left(), rcTitle.top(), X - rcTitle.left(),
                 rcTitle.bottom() - rcTitle.top());
  painter.setPen(QPen(crText));
  painter.setFont(QFont(m_currentFont));
  painter.drawText(textRect, szTitle,
                   QTextOption(Qt::AlignRight | Qt::AlignVCenter));

  // 新密码
  szTitle = NewStringTable::strDlgAlterPassword(12);  //_T("新密码 : ");
  textRect.adjust(0, lineHeight, 0, lineHeight);
  painter.setPen(QPen(crText));
  painter.setFont(QFont(m_currentFont));
  painter.drawText(textRect, szTitle,
                   QTextOption(Qt::AlignRight | Qt::AlignVCenter));

  // 确认密码
  szTitle = NewStringTable::strDlgAlterPassword(13);  //_T("确认密码 : ");
  textRect.adjust(0, lineHeight, 0, lineHeight);
  painter.setPen(QPen(crText));
  painter.setFont(QFont(m_currentFont));
  painter.drawText(textRect, szTitle,
                   QTextOption(Qt::AlignRight | Qt::AlignVCenter));

  m_rcTip = r;
  m_rcTip.setTop(rcEdit.bottom() + 1);
  m_rcTip.setBottom(rcEdit.bottom() + 24);

  QString szTip = m_strTip;
  if (szTip == tr("")) {
    szTip = NewStringTable::strDlgAlterPassword(18);
    szTip =
        QFontMetrics(m_currentFont)
            .elidedText(szTip, Qt::TextElideMode::ElideLeft, m_rcTip.width());
    crTip = NAME_COLOR("SupportingWord");
  }

  {
    QRect rcText = m_rcTip;
    QFontMetrics fontMetrics(m_currentFont);
    int nFontWidth = fontMetrics.width(szTip);
    int nFontHeight = fontMetrics.height();
    if (nFontWidth > rcText.width()) nFontWidth = rcText.width();

    rcText.setLeft(rcText.left() + (rcText.width() - nFontWidth) / 2);
    rcText.setTop(rcText.top() + (rcText.height() - nFontHeight) / 2);
    painter.setPen(QPen(crTip));
    painter.setFont(QFont(m_currentFont));
    painter.drawText(rcText, szTip,
                     QTextOption(Qt::AlignHCenter | Qt::AlignVCenter));
  }
}

void CDlgAlterPassword::paintEvent(QPaintEvent* event) {
  QPainter painter(this);

  QRect r = rect();
  painter.setRenderHint(QPainter::Antialiasing);
  painter.setBrush(QBrush(StyleMgr::instance().color("BasicPlate")));
  QPen pen1(StyleMgr::instance().color("InnerBorder"), 1);
  painter.setPen(pen1);
  painter.drawRoundedRect(r, StyleMgr::instance().size("RoundCorner"),
                          StyleMgr::instance().size("RoundCorner"));

  SPopupWindow::paintEvent(event);

  DrawMain();
}

void CDlgAlterPassword::CreateButton() {
  m_btnOk = new QPushButton("确定", this);
  QString style =
      QString(
          "QPushButton{background:#%1; "
          "border-radius:0px;color:#FFE5C7}\nQPushButton:hover{background:#%2}"
          "\nQPushButton:disabled{color:#585B5A;background:#263735}\n"
          "#%1{background:#0C4F44}\n}")
          .arg(StyleMgr::instance().color("ButtonNormal").rgb(), 0, 16)
          .arg(StyleMgr::instance().color("Hover").rgb(), 0, 16);
  m_btnOk->setStyleSheet(style);
  m_btnOk->setFixedSize(120, 24);

  m_btnCancel = new QPushButton("取消", this);
  m_btnCancel->setStyleSheet(style);
  m_btnCancel->setFixedSize(80, 24);
}
void CDlgAlterPassword::CreateEditCtrl(int w) {
  for (int i = 0; i < 3; i++) {
    arrEdit[i] = new QLineEdit(this);
    arrEdit[i]->setFixedSize(w, 24);
    arrEdit[i]->setEchoMode(QLineEdit::Password);
    QFont f = arrEdit[i]->font();
    f.setPixelSize(13);
    arrEdit[i]->setFont(f);
  }
}

void CDlgAlterPassword::OnBtnOk() { AlterPassword(); }

void CDlgAlterPassword::OnBtnCancel() { close(); }

void CDlgAlterPassword::AlterPassword() {
  QString csOldPas = tr("");
  QString cspas1 = tr("");
  QString cspas2 = tr("");
  csOldPas = arrEdit[0]->text();
  cspas1 = arrEdit[1]->text();
  cspas2 = arrEdit[2]->text();
  if (csOldPas.isEmpty() || cspas1.isEmpty() || cspas2.isEmpty()) {
    DisplayTipError(
        NewStringTable::strDlgAlterPassword(14));  //_T("密码不能为空!"));
    return;
  }
  if (cspas1 != cspas2) {
    DisplayTipError(
        NewStringTable::strDlgAlterPassword(15));  //_T("两次密码输入不一致!"));
    return;
  }

  int nLen = cspas1.length();
  if (nLen < nMinSize || nLen > nMaxSize) {
    DisplayTipError(NewStringTable::strDlgAlterPassword(
        19));  //_T("密码必须是8-20位数字、英文字母组合。"));
    return;
  }

  QByteArray wcpas1 = cspas1.toUtf8();
  uint nCheck = 0;
  int nIndex = 0;
  for (; nIndex < nLen; nIndex++) {
    int pwd = int(wcpas1.at(nIndex));
    if (pwd >= 48 && pwd <= 57)  // 0-9
    {
      nCheck |= nNum;
      continue;
    } else if (pwd >= 65 && pwd <= 90)  // A-Z
    {
      nCheck |= nNum;
      continue;
    } else if (pwd >= 97 && pwd <= 122)  // a-z
    {
      nCheck |= nChat;
      continue;
    } else {
      nCheck = 0;
      break;
    }
  }

  if (nCheck != nBoth) {
    DisplayTipError(NewStringTable::strDlgAlterPassword(
        19));  //_T("密码必须是8-20位数字、英文字母组合。"));
    return;
  }

  m_strTip = tr("");
  CUserAccountInfo& usrInfo = SSUserAccountManager::instance().GetUserInfo();

  char cOldPas[33] = {0};
  char cPas[33] = {0};
  FIELDCOPY(cOldPas, csOldPas.toStdString().c_str());
  FIELDCOPY(cPas, cspas1.toStdString().c_str());

  char* cMd5OldPas = qb::MD5String(cOldPas);
  char* cMd5NewPas = qb::MD5String(cPas);

  if (strcmp(cMd5OldPas, usrInfo.m_Password) != 0) {
    DisplayTipError(
        NewStringTable::strDlgAlterPassword(17));  //_T("原密码输入错误!"));
    return;
  }
  if (strcmp(cMd5NewPas, usrInfo.m_Password) == 0) {
    DisplayTipError(
        NewStringTable::strDlgAlterPassword(16));  //_T("新密码与原密码相同!"));
    return;
  }

  m_NewPass = cPas;
  char* cMd5Pas = qb::MD5String(cPas);
  QBAccountInfoMdfReq_t m_Req;
  memset(&m_Req, 0, sizeof(QBAccountInfoMdfReq_t));
  FIELDCOPY(m_Req.m_OldPassword, cMd5OldPas);
  FIELDCOPY(m_Req.m_Password, cMd5Pas);
  FIELDCOPY(m_Req.m_UserId, usrInfo.m_UserId);

  qb::SSRequestMsg msg;
  msg.m_pRequest = &m_Req;
  msg.m_FuncID = E_FID_QB_MODIFY_PASSWORD;
  MessagePoster poster(&msg, auth::EncodeFunc);
  poster.send(this);

  SetEnableBtn(false);
  free(cMd5OldPas);
  free(cMd5Pas);
}
void CDlgAlterPassword::DisplayTipError(QString text) { m_strTip = text; }

void CDlgAlterPassword::SetEnableBtn(bool bEnable) {
  m_btnOk->setEnabled(bEnable);
}
// CDlgAlterPassword 消息处理程序
